#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/10/4 12:01
# @Author  : AshJo
# @Desc    : socket_server_client
# @Filename: client.py
# @Version : v1.0
"""

import os
import sys
import json
import struct
import socket




sk = socket.socket()
sk.connect(('127.0.0.1', 9000))

while True:
    sk.send(b'hello world!')
    content = sk.recv(1024).decode('utf-8')
    print(content)



# 下载
def download(sk):
    opt_dic = {'operate': 'download'}
    my_send(sk, opt_dic)
    msg = my_recv(sk)
    with open(msg['filename'], mode='wb') as f:
        while msg['filesize'] > 0:
            content = sk.recv(1024)
            msg['filesize'] -= len(content)
            f.write(content)

# 上传
def upload(sk):
    opt_dic = {'operate': 'upload'}
    my_send(sk, opt_dic)
    abs_path = r'D:\Zend\livecut.mp4'
    filename = os.path.basename(abs_path)
    filesize = os.path.getsize(abs_path)
    dic = {'filename': filename, 'filesize': filesize}
    print(dic)
    my_send(sk, dic)
    with open(abs_path, mode='rb') as f:
        while filesize > 0:
            content = f.read(1024)
            filesize -= len(content)
            sk.send(content)


# 发送
def my_send(sk, dic):
    str_dic = json.dumps(dic)
    b_dic = str_dic.encode('utf-8')
    mlen = struct.pack('i', len(b_dic))
    sk.send(mlen)
    sk.send(b_dic)


# 接收
def my_recv(sk):
    msg_len = sk.recv(4)
    dic_len = struct.unpack('i', msg_len)[0]
    msg = sk.recv(dic_len).decode('utf-8')
    msg = json.loads(msg)
    return msg


def login(sk):
    while True:
        username = input('用户名：').strip()
        password = input('密码：').strip()
        dic = {'username': username, 'password': password}
        my_send(sk, dic)
        ret = my_recv(sk)
        if ret['operate'] == 'login' and ret['result'] is True:
            print('登录成功！')
            break
        else:
            print('登录失败！')


sk = socket.socket()
sk.connect(('127.0.0.1', 9000))

# 登录
login(sk)

# 上传/下载
choose_lst = ['upload', 'download']
for index, opt in enumerate(choose_lst, 1):
    print(index, opt)
num = int(input('请输入要选择的操作：'))
getattr(sys.modules[__name__], choose_lst[num - 1])(sk)